package com.coderman.common.starter.tianqing.qlexpress.service;

import com.ql.util.express.ExpressRunner;
import com.ql.util.express.IExpressContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * Description:
 * date: 2020/10/14
 *
 * @author fanchunshuai
 * @version 1.0.0
 * @since JDK 1.8
 */
@Service(value = "springQlExpressRunner")
public class SpringQlExpressRunner implements ApplicationContextAware {
    private Logger logger = LoggerFactory.getLogger(this.getClass());


    private ApplicationContext applicationContext;
    private ExpressRunner runner;


    @Override
    public void setApplicationContext(ApplicationContext context)  throws BeansException{
        this.applicationContext = context;
        runner = new ExpressRunner();
    }

    public Object executeExpress(String text, Map<String,Object> context)
    {
        IExpressContext<String,Object> expressContext = new SpringQlExpressBeanContext(context,this.applicationContext);
        try{
            return runner.execute(text, expressContext, null, true, false);
        }catch(Exception e){
            logger.error("qlExpress运行出错！",e);
        }
        return null;

    }

    /**
     * 当有配置更新的时候清空缓存
     */
    public void clearQlExpressCache(){
        runner.clearExpressCache();
    }

}
